package com.zl.learning.thread.forkjoin;

import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class CountTask2 extends RecursiveTask<Integer> {

    private List<Integer> list;

    public CountTask2(List<Integer> list) {
        this.list = list;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //如果任务足够小就计算
        while (list.size() > 2) {
            Spliterator<Integer> spliterator = list.spliterator();
//            spliterator.
        }
//        boolean canCompute = (end - start) <= THREAD_HOLD;
//        if (canCompute) {
//            for (int i = start; i <= end; i++) {
//                sum += i;
//            }
//        } else {
//            int middle = (start + end) / 2;
//            CountTask2 left = new CountTask2(start, middle);
//            CountTask2 right = new CountTask2(middle + 1, end);
//            //执行子任务
//            left.fork();
//            right.fork();
//            //获取子任务结果
//            int lResult = left.join();
//            int rResult = right.join();
//            sum = lResult + rResult;
//        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        CountTask2 task = new CountTask2(IntStream.range(0, 10).boxed().collect(Collectors.toList()));
        Future<Integer> result = pool.submit(task);
        try {
            System.out.println(result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
